﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Sql;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;

namespace PersonaLibrary.ViewModel.PropertiesViewModel
{
	internal class MainPropertiesVM : BaseViewModel<View.PropertiesView.Properties>
	{
		private string _selectedElement;
		private string _pointerValueTemplate = @"^\w$";
		private Metadata.Point _selectedPoint;
		private List<Metadata.Point> _points;

		private RelayCommand _saveCommand;

		public MainPropertiesVM()
		{
			Dispatcher.Thread.Priority = ThreadPriority.BelowNormal;
			Elements = new List<string> { Mapping.Mapper.Instance.Convert(typeof(Data.Employee).Name), 
				Mapping.Mapper.Instance.Convert(typeof(Data.Organization).Name) };
			if (Elements.Count != 0)
				SelectedElement = Elements[0];
		}

		public List<string> Elements { private set; get; }

		public RelayCommand SaveCommand
		{
			get
			{
				if(_saveCommand == null)
					_saveCommand = new RelayCommand(x => Save(), x => CanSave(x));
				return _saveCommand;
			}
		}

		public string SelectedElement
		{
			set
			{
				_selectedElement = value;
				CustomProperty = Properties.Settings.Default.SpecializeProperties[Mapping.Mapper.Instance.Convert(value)];
				Points = Metadata.Instance[Mapping.Mapper.Instance.Convert(SelectedElement)].Where(x => x.IsFilter).ToList();
				SelectedPoint = Points.SingleOrDefault(x => x.Name == CustomProperty.AlphabetFilterProperty);
				RisePropertyChanged("CustomProperty");
				RisePropertyChanged("PointerValue");
			}
			get { return _selectedElement; }
		}

		private void Save()
		{
			Properties.Settings.Default.SpecializeProperties[Mapping.Mapper.Instance.Convert(SelectedElement)] = CustomProperty;
			Properties.Settings.Default.Save();
			View.Close();
		}

		private bool CanSave(object arg)
		{
			return true;
		}

		public CustomProperties.PropertiesItem CustomProperty { private set; get; }

		public List<Metadata.Point> Points
		{
			get { return _points; }
			set
			{
				_points = value;
				RisePropertyChanged("Points");
			}
		}

		public Metadata.Point SelectedPoint
		{
			get
			{
				return _selectedPoint;
			}
			set
			{
				_selectedPoint = value;
				RisePropertyChanged("SelectedPoint");
				if(_selectedPoint != null)
					CustomProperty.AlphabetFilterProperty = _selectedPoint.Name;
			}
		}

		public string PointerValue
		{
			set
			{
				if (Regex.IsMatch(value, _pointerValueTemplate))
					CustomProperty.AlphabetFilterValue = value;

				RisePropertyChanged("PointerValue");
			}
			get
			{
				if (CustomProperty != null)
					return CustomProperty.AlphabetFilterValue;
				return null;
			}
		}
	}
}
